import csv
from django.core.management import BaseCommand
from django.contrib.auth.models import User
class Command(BaseCommand):
    help = "导入CSV"

    def add_arguments(self, parser):
        parser.add_argument("--path", type=str)

    def handle(self, *args, **options):
        path = options['path']
        with open(path, 'r',encoding='utf-8') as f:
            reader = csv.reader(f)
            header = reader.__next__()
            print(header)
            for row in reader:
                user_obj = dict(zip(header, row))
                user_in = User.objects.get_by_natural_key(username=row[0])
                if not user_in:
                    candidate = User.objects.create_user(
                        **user_obj
                    )
                    print(candidate)
                else:
                    print("user {} exists!".format(user_in))